﻿#include "mainwindow.h"
#include "treeitem2.h"
#include "treemodel2.h"
#include "ui_mainwindow.h"
#include <QStandardItemModel>

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    initClassData();

    //    ui->treeView = new QTreeView(this);
    ui->treeView->setSelectionBehavior(QTreeView::SelectRows);  //一次选中整行
    ui->treeView->setSelectionMode(QTreeView::SingleSelection); //单选，配合上面的整行就是一次选单行
    ui->treeView->setFocusPolicy(Qt::NoFocus);                  //去掉鼠标移到单元格上时的虚线框
    ui->treeView->header()->setStretchLastSection(true);        //最后一列自适应宽度
    // treeView->setHeaderHidden(true);                                //设置表头隐藏
    setCentralWidget(ui->treeView);

    QVector<Department *> proList = initData();
    setModel(proList);
}

MainWindow::~MainWindow()
{
    delete ui;
}
void MainWindow::setModel(const QVector<Department *> &proList)
{
    QStringList headers;
    headers << QStringLiteral("部门名称") << QStringLiteral("部门Id") << QStringLiteral("部门人数") << QStringLiteral("上级部门");

    TreeModel *model = new TreeModel(headers, ui->treeView);
    TreeItem *root = model->root();
    foreach (auto depNode, proList)
    {
        TreeItem *depItem = new TreeItem(root);
        depItem->setPtr(depNode); // 保存数据指针
        root->addChild(depItem);

        foreach (auto subNode, depNode->subList)
        {
            TreeItem *subItem = new TreeItem(depItem);
            subItem->setPtr(subNode); // 保存数据指针
            depItem->addChild(subItem);
        }
    }

    ui->treeView->setModel(model);
}

QVector<Department *> MainWindow::initData()
{
    QVector<Department *> proList;
    for (int i = 0; i < 10; i++)
    {
        Department *topDepartment = new Department();
        topDepartment->id = i;
        topDepartment->name = QString("departMent%1").arg(i);
        for (int j = 0; j < 5; ++j)
        {
            Department *subDepartment = new Department();
            subDepartment->id = j;
            subDepartment->name = QString("childPartMent%1").arg(j);

            topDepartment->subList.append(subDepartment);
        }

        proList.append(topDepartment);
    }
    return proList;
}
void MainWindow::initClassData()
{
}

void MainWindow::addUserDefineData()
{
}

void MainWindow::on_btn_addUserDefineData_clicked()
{
}
